<script setup>
import { ref } from "vue";
import {
  negotiationApi,
  negRefuseApi,
  negCancelApi,
  negPayApi,
} from "@/services/order";
import { mine, isPayPassApi, checkPayPass } from "@/services/user";
import { onLoad, onShow, onReachBottom } from "@dcloudio/uni-app";
import { formatPrice } from "@/utils/formatPrice";

import wxicon from "@/static/cloudlibrary/icon_weixin.png";
import yeicon from "@/static/cloudlibrary/icon_yue.png";
import dficon from "@/static/cloudlibrary/icon_daifu.png";

onLoad((e) => {
  getList();
  negotiationData.value.type = e.type ? e.type : negotiationData.value.type;
});

onShow(() => {
  isPayPassFun();
});

const list1 = ref([
  { name: "全部", value: "" },
  { name: "待支付", value: 0 },
  { name: "已支付", value: 5 },
  { name: "已取消", value: -5 },
]);

const keyword = ref("");

const negotiationData = ref({
  type: 1,
  status: "",
  keyword: "",
  page: 1,
  limit: 20,
});

const negotiationList = ref([]);
const status = ref("more");

const payClick = (e) => {
  negotiationData.value.type = e;
  negotiationList.value = [];
  negotiationData.value.page = 1;
  getList();
};

// 代付订单详情
const orderDeatil = (item) => {
  uni.navigateTo({
    url: "/pages/mine/proxyPaymentDetails?id=" + item.id,
  });
};

// 拒绝
const showRefuse = ref(false);
const refuse = (id) => {
  showRefuse.value = true;
  refuseData.value.id = id;
};

const refuseData = ref({});

// 拒绝-确认按钮
const refuseSubmit = async () => {
  try {
    // 发送请求
    let res = await negRefuseApi(refuseData.value);
    if (res.code == 200) {
      showRefuse.value = false;
      uni.showToast({
        title: res.info,
        icon: "success",
      });
      negotiationList.value = [];
      negotiationData.value.page = 1;
      getList();
    }
  } catch (e) {
    showRefuse.value = false;
    uni.showToast({
      title: e.info,
      icon: "none",
    });
    negotiationList.value = [];
    negotiationData.value.page = 1;
    getList();
  }
};

// 撤回
const showRevoke = ref(false);
const revoke = (id) => {
  showRevoke.value = true;
  revokeData.value.id = id;
};

const revokeData = ref({});

// 撤回-确认按钮
const revokeSubmit = async () => {
  try {
    // 发送请求
    let res = await negCancelApi(revokeData.value);
    if (res.code == 200) {
      showRevoke.value = false;
      uni.showToast({
        title: res.info,
        icon: "success",
      });
      negotiationList.value = [];
      negotiationData.value.page = 1;
      getList();
    }
  } catch (e) {
    showRevoke.value = false;
    uni.showToast({
      title: e.info,
      icon: "none",
    });
    negotiationList.value = [];
    negotiationData.value.page = 1;
    getList();
  }
};

// 去支付
const showgoPay = ref(false);
const pay_type = ref(1);
const balance = ref(0);
const paylist = ref([
  {
    title: "2",
    des: "微信支付（推荐）",
    icon: wxicon,
  },
  {
    title: "1",
    des: "余额支付 ",
    icon: yeicon,
  },
  // {
  //   title: "7",
  //   des: "他人代付",
  //   icon: dficon,
  // },
]);

// 查询用户余额
const mineFun = async () => {
  try {
    // 发送请求
    let res = await mine();
    if (res.code == 200) {
      balance.value = res.data.balance;
      if (balance.value < total_price.value) {
        pay_type.value = 2;
      }
    }
  } catch (e) {
    uni.showToast({
      title: e.info,
      icon: "none",
    });
  }
};

const close = () => {
  showgoPay.value = false;
  showRefuse.value = false;
  showPassword.value = false;
  showRevoke.value = false;
  focusinput.value = false;
  pay_pass.value = "";
};
const total_price = ref(0);
const goPay = (item, index) => {
  selectindex.value = index;
  showgoPay.value = true;
  goPayData.value.id = item.id;
  total_price.value = item.orders.total_price;
  mineFun();
};

const goPayData = ref({});
function onBridgeReady(yishen) {
  WeixinJSBridge.invoke("getBrandWCPayRequest", yishen, (res) => {
    showgoPay.value = false;
    if (res) {
      negotiationList.value = [];
      getList();
      // 使用以上方式判断前端返回,微信团队郑重提示：
      //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
    }
  });
}

const isPayPass = ref(0);
const isPayPassFun = async () => {
  try {
    let res = await isPayPassApi();
    if (res.code == 200) {
      isPayPass.value = res.data;
    }
  } catch (e) {
    uni.showToast({
      title: e.info,
      icon: "none",
    });
  }
};

const showPassword = ref(false);
const pay_pass = ref("");
const gopassword = () => {
  if (
    goPayData.value.pay_type == 1 &&
    balance.value < negotiationList.value[0].orders.total_price
  ) {
    uni.showToast({
      title: "余额不足，无法支付",
      icon: "success",
    });
    return;
  }
  if (pay_type.value == 1 && isPayPass.value != 0) {
    showPassword.value = true;
    pay_pass.value = "";
    setTimeout(() => {
      focusinput.value = true;
    }, 500);
  } else if (pay_type.value == 1 && isPayPass.value == 0) {
    uni.showToast({
      title: "没有支付密码，前往设置",
      icon: "none",
    });

    setTimeout(() => {
      uni.navigateTo({
        url: "/pages/mysetting/modify/index?isshowPassword=" + isPayPass.value,
      });
    }, 500);
  }
  if (pay_type.value == "2" || pay_type.value == "7") {
    goPaySubmit();
  }
};

const selectindex = ref(0);

const gocancle = () => {
  showPassword.value = false;
  pay_pass.value = "";
};

// 去支付-确认按钮

const goPaySubmit = async () => {
  let res = null;
  let yishen = null;
  try {
    if (pay_type.value == "1") {
      res = await negPayApi({
        ...goPayData.value,
        pay_type: 1,
        pay_pass: pay_pass.value,
      });
    }
    if (pay_type.value == "2") {
      try {
        // #ifdef H5
        res = await negPayApi({ ...goPayData.value, pay_type: 2 });
        yishen = JSON.parse(res.data.wxWcPayData);

        if (typeof WeixinJSBridge == "undefined") {
          if (document.addEventListener) {
            document.addEventListener(
              "WeixinJSBridgeReady",
              onBridgeReady(yishen),
              false
            );
          } else if (document.attachEvent) {
            document.attachEvent("WeixinJSBridgeReady", onBridgeReady(yishen));
            document.attachEvent(
              "onWeixinJSBridgeReady",
              onBridgeReady(yishen)
            );
          }
        } else {
          onBridgeReady(yishen);
        }
        // #endif

        // #ifdef MP-WEIXIN

        res = await negPayApi({ ...goPayData.value, pay_type: 3 });
        // yishen = JSON.parse(res.data.wxWcPayData);
        yishen = res.data;
        if (res.code == 200) {
          // 仅作为示例，非真实参数信息。
          uni.requestPayment({
            provider: "wxpay",
            timeStamp: yishen.timeStamp,
            nonceStr: yishen.nonceStr,
            package: yishen.package,
            signType: yishen.signType,
            paySign: yishen.paySign,
            success: function (res) {
              uni.showToast({
                title: "支付成功",
                icon: "none",
              });
              getList();
            },
            fail: function (err) {
              uni.showToast({
                title: "取消支付",
                icon: "none",
              });
            },
          });
        } else {
          uni.showToast({
            title: "支付失败",
            icon: "none",
          });
        }
        // #endif
        return;
      } catch (e) {
        uni.showToast({
          title: e.info,
          icon: "none",
        });
      }
    }

    if (res.code == 200) {
      uni.showToast({
        title: "支付成功",
        icon: "none",
      });
      negotiationList.value.splice(selectindex.value, 1);
      showgoPay.value = false;
      showPassword.value = false;
      focusinput.value = false;
      pay_pass.value = "";
      getList();
    } else {
      uni.showToast({
        title: res.info,
        icon: "none",
      });
      pay_pass.value = "";
    }
  } catch (e) {
    uni.showToast({
      title: e.info,
      icon: "none",
    });
    pay_pass.value = "";
    negotiationList.value = [];
    negotiationData.value.page = 1;
    getList();
  }
};

// 定义方法
function clicktabs(item) {
  negotiationData.value.status = item.value;
  negotiationList.value = [];
  negotiationData.value.page = 1;
  getList();
}

// 搜索
const searchfun = () => {
  negotiationList.value = [];
  negotiationData.value.page = 1;
  negotiationData.value.keyword = keyword.value;
  getList();
};

//下拉触底
onReachBottom(() => {
  // 触发下拉触底时执行的操作
  getList();
});

const getList = async () => {
  try {
    status.value = "loading";
    // 发送请求
    let res = await negotiationApi(negotiationData.value);
    let arr = [];
    arr = res.data.list;
    negotiationList.value = negotiationList.value.concat(arr);
    if (res.data.list.length < negotiationData.value.limit) {
      status.value = "no-more";
    } else {
      status.value = "more";
    }
    negotiationData.value.page++;
  } catch (e) {
    uni.showToast({
      title: e.info,
      icon: "none",
    });
  }
};

const callPhone = (phoneNumber) => {
  // 判断手机是否支持拨打电话功能
  if (uni.canIUse("makePhoneCall")) {
    uni.makePhoneCall({
      phoneNumber: phoneNumber, // 电话号码
      success: function () {},
      // fail: function () {
      //   uni.showToast({
      //     title: "拨打电话失败",
      //     icon: "error",
      //   });
      // },
    });
  } else {
    uni.showToast({
      title: "你的设备不支持拨打电话功能",
      icon: "none",
    });
  }
};

const selectpayfun = async (type) => {
  if (balance.value < total_price.value && type == 1) {
    uni.showToast({
      title: "余额不足",
      icon: "none",
    });
    return;
  }
  pay_type.value = type;
};

// 定义 finish 方法
const finish = async (e) => {
  pay_pass.value = e;
  try {
    let res = await checkPayPass({ pay_pass: pay_pass.value });
    if (res.code == 200) {
      goPaySubmit();
    }
  } catch (e) {
    uni.showToast({
      title: e.info,
      icon: "none",
    });
    pay_pass.value = "";
  }
};

const forgot = () => {
  uni.navigateTo({
    url: "/pages/mysetting/modify/index?isshowPassword=" + isPayPass.value,
  });
};

const focusinput = ref(false);
</script>
<template>
  <view class="changeRecord">
    <view class="changeRecord-search">
      <u-search
        :placeholder="
          negotiationData.type == 1 ? '付款人/订单编号' : '申请人/订单编号'
        "
        :clearabled="true"
        :show-action="false"
        v-model="keyword"
        @search="searchfun"
      ></u-search>
    </view>
    <view class="changeRecord-top">
      <view class="changeRecord-top-tabs"
        ><up-tabs
          :activeStyle="{
            color: '#F3498B ',
            fontSize: '28rpx',
            fontWeight: '500',
          }"
          :inactiveStyle="{
            color: '#8C8C8C',
            fontWeight: '500',
            fontSize: '28rpx',
          }"
          lineColor="#F3498B "
          itemStyle="padding-left: 50rpx; padding-right: 50rpx; height: 34px;"
          :list="list1"
          @click="clicktabs"
        ></up-tabs
      ></view>
    </view>

    <view v-show="negotiationList && negotiationList.length > 0">
      <view
        class="foodr-list"
        v-for="(item, index) in negotiationList"
        :key="index"
      >
        <view class="list-index">
          <view class="list-index-left">
            {{
              item.user && negotiationData.type == 1
                ? "代付付款人"
                : "代付申请人"
            }}：{{
              item.user && negotiationData.type == 1
                ? item.user.nickname
                : item.buyer && negotiationData.type == 2
                ? item.buyer.nickname
                : "---"
            }}
            <image
              src="@/static/team/shopkeeper/phone-icon.png"
              mode="widthFix"
              @click="
                callPhone(
                  item.user && negotiationData.type == 1
                    ? item.user.phone
                    : item.buyer && negotiationData.type == 2
                    ? item.buyer.phone
                    : ''
                )
              "
            ></image>
          </view>
          <view
            class="list-index-right"
            :class="
              item.status == 0
                ? 'list-index-right'
                : item.status == 5
                ? 'paidAlready'
                : item.status == -5
                ? 'cancelled'
                : ''
            "
            >{{ item.status_text }}</view
          >
        </view>
        <u-line length="85%" class="notuse-line"></u-line>
        <view class="list-middle">
          <view class="list-middle-left">
            <view class="middle-left-top"
              >订单信息：{{ item.orders.order_info || "---" }}</view
            >
            <view class="middle-left-top"
              >订单编号：{{ item.orders.order_id
              }}<up-copy :content="item.orders.order_id"
                ><image
                  src="@/static/my/copy-img.png"
                  mode="widthFix" /></up-copy
            ></view>
          </view>
          <view class="list-middle-money"
            >¥{{ formatPrice(item.orders.total_price) }}</view
          >
        </view>
        <u-line length="85%" class="notuse-line"></u-line>

        <view class="foodr-list-btn">
          <view class="footer-btn" @click="orderDeatil(item)">订单详情</view>
          <view
            class="footer-btn"
            v-if="negotiationData.type == 2 && item.status == 0"
            @click="refuse(item.id)"
            >拒绝支付</view
          >
          <view
            class="footer-btn"
            v-if="negotiationData.type == 1 && item.status == 0"
            @click="revoke(item.id)"
            >撤回申请</view
          >
          <view
            class="footer-btn goPay"
            v-if="item.status == 0 && negotiationData.type == 2"
            @click="goPay(item, index)"
            >去支付</view
          >
        </view>
      </view>
    </view>

    <view class="nodate-bt" v-if="negotiationList.length === 0">
      <image src="/static/nodate/nodate.png" mode="widthFix"></image>
    </view>

    <uni-load-more color="#c6c5c3" :status="status" />

    <view class="footer-bt">
      <view class="bt-submit">
        <view class="bt-submit-left" @click="payClick((type = 1))">
          <view class="footer-box">
            <view class="footer-img">
              <!-- <image
                src="@/static/my/give-green.png"
                mode="widthFix"
                v-if="negotiationData.type == 1" />
              <image src="@/static/my/give-black.png" mode="widthFix" v-else /> -->
              <image
                :src="
                  negotiationData.type == 1
                    ? '../../static/my/give-green.png'
                    : '../../static/my/give-black.png'
                "
                mode="widthFix"
              />
            </view>
            <view
              :class="
                negotiationData.type == 1 ? 'footer-text-active' : 'footer-text'
              "
              >我发起的代付</view
            >
          </view>
        </view>
        <view class="bt-submit-left" @click="payClick((type = 2))">
          <view class="footer-box">
            <view class="footer-img">
              <!-- <image src="@/static/my/money-green.png" mode="widthFix" /> -->
              <!-- <image src="@/static/my/money-black.png" mode="widthFix" /> -->
              <image
                :src="
                  negotiationData.type == 2
                    ? '../../static/my/money-green.png'
                    : '../../static/my/money-black.png'
                "
                mode="widthFix"
              />
            </view>
            <view
              :class="
                negotiationData.type == 2 ? 'footer-text-active' : 'footer-text'
              "
              >我支付的代付</view
            >
          </view>
        </view>
      </view>
    </view>

    <!-- 拒绝支付弹框 -->
    <u-popup
      :show="showRefuse"
      mode="center"
      round="10"
      @close="close"
      @open="open"
    >
      <view class="productGift">
        <view class="popup-content-title">温馨提示</view>
        <view class="popup-content-item"
          >拒绝支付无法撤回，请确认拒绝支付？</view
        >
        <view class="popup-content-box">
          <view class="popup-content-bt">
            <u-button
              class="popup-content-qx"
              text="取消"
              @click="showRefuse = false"
            ></u-button>
            <u-button
              class="popup-content-cl"
              text="确定拒绝"
              @click="refuseSubmit"
            ></u-button>
          </view>
        </view>
      </view>
    </u-popup>

    <!-- 撤回申请弹框 -->
    <u-popup
      :show="showRevoke"
      mode="center"
      round="10"
      @close="close"
      @open="open"
    >
      <view class="productGift">
        <view class="popup-content-title">温馨提示</view>
        <view class="popup-content-item"
          >撤回申请无法回退，请确认撤回申请？</view
        >
        <view class="popup-content-box">
          <view class="popup-content-bt">
            <u-button
              class="popup-content-qx"
              text="取消"
              @click="showRevoke = false"
            ></u-button>
            <u-button
              class="popup-content-cl"
              text="确定撤回"
              @click="revokeSubmit"
            ></u-button>
          </view>
        </view>
      </view>
    </u-popup>

    <!-- 去支付弹框 -->
    <up-popup v-model:show="showgoPay" :round="10" @close="close">
      <view class="content-pay">
        <view
          class="content-pay-item"
          v-for="(item, index) in paylist"
          :key="index"
          @click="selectpayfun(item.title)"
        >
          <view
            :class="
              balance < total_price && item.title == 1
                ? 'content-pay-left noselect'
                : 'content-pay-left'
            "
          >
            <image :src="item.icon" mode="widthFix" />
            <text>{{ item.des }}</text>
            {{ item.title == 1 ? "(可用" + balance + "元)" : "" }}
          </view>
          <view class="content-pay-right" v-if="pay_type == item.title">
            <image src="@/pages/mine/static/select.png" mode="widthFix" />
          </view>
        </view>
        <up-button
          @click="gopassword"
          class="custom-style"
          text="确认支付"
        ></up-button>
      </view>
    </up-popup>

    <!-- 密码弹框 -->
    <u-popup
      :show="showPassword"
      mode="center"
      round="10"
      @close="close"
      @open="open"
    >
      <view class="password">
        <view class="popup-content-title">支付密码</view>
        <u-code-input
          v-model="pay_pass"
          :maxlength="6"
          dot
          size="80"
          @change="onChange"
          @finish="finish"
          :focus="focusinput"
        ></u-code-input>
        <view class="footer">
          <view class="closefun" @click="showPassword = false">取消</view>
          <view class="forgot" @click="forgot">忘记密码？</view>
        </view>
      </view>
    </u-popup>
  </view>
</template>
<style lang="scss" scoped>
@import "proxyPayment.scss";
</style>
